﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ManageLiteAV;
using TRTCMain.Properties;
using TCommon.Entity;
using TCommon;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Threading;
using TRTCCSharpDemo;
using System.Diagnostics;
using TCommon.Util;

namespace TRTCMain.Controls
{
    public partial class VideoContainer : UserControl
    {
        private SortedDictionary<string, UserVideoItem> videoDic = new SortedDictionary<string, UserVideoItem>();
        private Dictionary<string, Panel> shareDic = new Dictionary<string, Panel>();
        //当前屏幕用户
        public static List<string> normalScreenUsers = new List<string>();

        public delegate void normalScreenUserChangedHandler(string userId, bool isAdd);
        public event normalScreenUserChangedHandler NormalScreenUserChanged;
        private SortedDictionary<string, Panel> enableNoneFocuseDic = new SortedDictionary<string, Panel>();
        private List<string> nameList = new List<string>();
        private List<string> foucseNameList = new List<string>();
        private Tuple<int, int, Point, string> maximizeCach;
        private Control maximizeParentCach;
        private bool isMaximized = false;
        private int videoSpace = 5;
        private string focusUser = "";
        private VideoLayoutType layoutType = VideoLayoutType.Normal;
        private Panel screenSharePanel;
        private ITRTCCloud mTRTCCloud;
        private int MaxNormalVideoCount = 4;
        private int MaxFocuseVideoCount = 4;
        private int RowSize = 1;
        public bool isFullScreen = false;
        private FullScreenButton fullscreenButton = null;
        private List<string> initializelist = new List<string>();
        public string HostName { get; set; }

        private Dictionary<string, Tuple<int, int, Point, Control>> shareCachDic = new Dictionary<string, Tuple<int, int, Point, Control>>();

        private int smallVideoWidth = 200;
        private int smallVideoHeight = 100;

        private int currentPageIndex = 0;

        public delegate void ButtonChangeHander(bool normalShow, bool smallShow);
        public event ButtonChangeHander ButtonChanged;

        //右击设置焦点时使用
        public delegate void FocuseUserChangeHandler(string userId);
        public event FocuseUserChangeHandler FocusedUserChanged;

        public delegate void VideoLayoutChangedHandler();
        public event VideoLayoutChangedHandler VideoLayoutChanged;

        public delegate void FullScreenChangeHandler(bool isFullScreen);
        public event FullScreenChangeHandler FullScreenChanged;
        public VideoContainer()
        {
            InitializeComponent();
            this.BackColor = Color.Black;
            //var picture = new PictureBox();
            //picture.Click += FullScreenClick;
            //picture.SizeMode = PictureBoxSizeMode.StretchImage;
            //picture.Size = new Size(80, 26);
            //picture.Location = new Point(this.Width - picture.Width - 5, 5);
            //picture.Anchor = AnchorStyles.Right | AnchorStyles.Top;
            //picture.Image = Resources.enterfull;
            //picture.BackColor = Color.FromArgb(255, 126, 126, 126);
            //this.Controls.Add(picture);
            //picture.BringToFront();
            
            rightPanel.Visible = false;
        }

        public void InitVideoContainer(Control control) {
            this.fullscreenButton = (FullScreenButton)control;
            this.fullscreenButton.Click += FullScreenClick;
        }

        public void ActivateForm()
        {
            if (screenSharePanel != null)
            {
                screenSharePanel.BringToFront();
            }
        }

        public void SetClound(ITRTCCloud mTRTCCloud)
        {
            this.mTRTCCloud = mTRTCCloud;
        }

        public List<Tuple<int, int, int, int, string>> GetLocations()
        {
            var list = new List<Tuple<int, int, int, int, string>>();

            if (screenSharePanel != null && screenSharePanel.Visible == true)
            {
                //var left = screenSharePanel.Location.X;
                //var top = screenSharePanel.Location.Y;
                //var right = screenSharePanel.Location.X + screenSharePanel.Width;
                //var bottom = screenSharePanel.Location.Y + screenSharePanel.Height;
                //var t = new Tuple<int, int, int, int, string>(left, top, right, bottom, screenSharePanel.Name);
                //list.Add(t);

                if (screenSharePanel.Controls.Count > 0)
                {
                    var vleft = screenSharePanel.Controls[0].Location.X;
                    var vtop = screenSharePanel.Controls[0].Location.Y;
                    var vright = screenSharePanel.Controls[0].Location.X + screenSharePanel.Width;
                    var vbottom = screenSharePanel.Controls[0].Location.Y + screenSharePanel.Height;
                    var user = $"share***{screenSharePanel.Controls[0].Tag}";
                    var tt = new Tuple<int, int, int, int, string>(vleft, vtop, vright, vbottom, user);
                    list.Add(tt);

                    if (screenSharePanel.Controls[0].Controls.Count > 0)
                    {
                        var smallVideo = screenSharePanel.Controls[0].Controls[0];
                        var left = smallVideo.Location.X;
                        var top = smallVideo.Location.Y;
                        var right = smallVideo.Location.X + screenSharePanel.Width;
                        var bottom = smallVideo.Location.Y + screenSharePanel.Height;
                        var suser = smallVideo.Name;
                        var t = new Tuple<int, int, int, int, string>(left, top, right, bottom, suser);
                    }
                }

                //foreach (var user in videoDic.Keys)
                //{
                //    if (!list.Exists(l => l.Item5 == user))
                //    {
                //        var t = new Tuple<int, int, int, int, string>(1, 1, 1, 1, user);
                //        list.Add(t);
                //    }
                //}

                return list;
            }

            if (layoutType == VideoLayoutType.Normal)
            {
                foreach (var key in normalScreenUsers)
                {
                    var left = videoDic[key].Location.X;
                    var top = videoDic[key].Location.Y;
                    var right = videoDic[key].Location.X + videoDic[key].Width;
                    var bottom = videoDic[key].Location.Y + videoDic[key].Height;
                    var t = new Tuple<int, int, int, int, string>(left, top, right, bottom, videoDic[key].Name);
                    list.Add(t);
                }
            }
            else
            {
                //foreach (var key in enableNoneFocuseDic.Keys)
                //{
                //    var left = this.Width - enableNoneFocuseDic[key].Width - 10;
                //    var top = enableNoneFocuseDic[key].Location.Y;
                //    var right = this.Width - 10;
                //    var bottom = enableNoneFocuseDic[key].Location.Y + enableNoneFocuseDic[key].Height;
                //    var t = new Tuple<int, int, int, int, string>(left, top, right, bottom, enableNoneFocuseDic[key].Name);
                //    list.Add(t);
                //}

                var focuseUser = videoDic[focusUser];
                var left = 0;
                var top = 0;
                var right = focuseUser.Width;
                var bottom = focuseUser.Height;
                var t = new Tuple<int, int, int, int, string>(left, top, right, bottom, focuseUser.Name);
                list.Add(t);
            }

            //foreach (var user in videoDic.Keys) {
            //    if (!list.Exists(l => l.Item5 == user)) {
            //        var t = new Tuple<int, int, int, int, string>(0, 0, 0, 0, user);
            //        list.Add(t);
            //    }
            //}

            return list;
        }

        public void ToggleLayout()
        {
            if (layoutType == VideoLayoutType.Normal)
            {
                if (videoDic.Count < 2)
                    return;

                layoutType = VideoLayoutType.Focus;
                //focusUser = HostName;
                rightPanel.Visible = true;
                foreach (var key in normalScreenUsers)
                {
                    if (videoDic[key].Name != "rightPanel")
                    {
                        this.Controls.Remove(videoDic[key]);
                    }
                }
                //this.Controls.Add(videoDic[focusUser]);
            }
            else
            {
                layoutType = VideoLayoutType.Normal;
                rightPanel.Visible = false;
                rightPanel.Controls.Clear();
                //foreach (var key in enableNoneFocuseDic.Keys)
                //{
                //    this.rightPanel.Controls.Remove(videoDic[key]);
                //}
            }

            UpdateEnableDict(0, true);
            ReorderVideo(true);
            RestMixConfig();
        }
        public IntPtr GetVideoHandle(string userName)
        {
            if (!videoDic.ContainsKey(userName))
            {
                AddPanel(userName);
            }
            //if (initializelist.Count >= 4)
            //{

            //}
            //else
            //{
            //    initializelist.Add(userName);
            //}

            return videoDic[userName].GetVideoPanel().Handle;
        }

        public IntPtr GetShareHandle(string userName, bool isShareByCurrentUser = false)
        {
            if (!shareDic.ContainsKey(userName))
            {
                AddSharePanel(userName);
                if (isShareByCurrentUser)
                {
                    fullscreenButton.Visible = false;
                }
                else
                {
                    fullscreenButton.Visible = true;
                }
            }

            return shareDic[userName].Handle;
        }

        public void RemoveShareHandle(string userName)
        {
            RemoveSharePanel(userName);
            fullscreenButton.Visible = true;
        }
        public void RemoveUser(string userName)
        {
            nameList.Remove(userName);
            if (initializelist.Contains(userName))
            {
                initializelist.Remove(userName);
            }
            if (videoDic.ContainsKey(userName))
            {
                if (layoutType == VideoLayoutType.Normal)
                {
                    this.Controls.Remove(videoDic[userName]);

                    if (videoDic.ContainsKey(userName)) {
                        videoDic.Remove(userName);
                    }

                    if (normalScreenUsers.Contains(userName))
                    {  
                        normalScreenUsers.Remove(userName);
                        NormalScreenUserChanged?.Invoke(userName, false);
                        UpdateCurrentPage();
                        //UpdateEnableDict(currentPageIndex, true);
                    }
                }
                else
                {
                    if (foucseNameList.Contains(userName))
                    {
                        rightPanel.Controls.Remove(videoDic[userName]);
                        videoDic.Remove(userName);
                        foucseNameList.Remove(userName);
                        UpdateCurrentPage();
                    }
                    else
                    {
                        this.Controls.Remove(videoDic[userName]);
                        videoDic.Remove(userName);
                    }



                    if (videoDic.Count == 1)
                    {
                        ToggleLayout();
                    }

                    if (userName == focusUser)
                    {
                        focusUser = HostName;
                    }
                }
            }
            UpdateEnableDict(currentPageIndex, true, true);
            ReorderVideo();
        }
        public UserList userList1 = null;
        public void userlist(UserList userList)
        {
            userList1 = userList;
        }
        public void AddPanel(string userName)
        {
            if (!videoDic.ContainsKey(userName))
            {
                var panel = new UserVideoItem();
                panel.Paint += Panel_Paint;
                panel.DoubleClick += PanelOnDoubleClick;
                panel.MouseClick += Panel_MouseClick;
                panel.Click += Panel_Click;
                panel.SetName(StringUtil.UserNameFromHex(userName));
                panel.Name = userName;
                panel.BackColor = Color.Transparent;
                panel.VisibleChanged += Panel_VisibleChanged;
                videoDic[userName] = panel;
                nameList.Add(userName);
                if (screenSharePanel != null && screenSharePanel.Visible)
                {
                    panel.Visible = false;
                }
                if (string.IsNullOrEmpty(focusUser))
                {
                    focusUser = HostName;
                }
                if (layoutType == VideoLayoutType.Normal)
                {
                    if (normalScreenUsers.Count < this.MaxNormalVideoCount)
                    {
                        //this.Controls.Add(panel);
                        //enabledDic[userName] = panel;
                        normalScreenUsers.Add(userName);
                        NormalScreenUserChanged?.Invoke(userName, true);
                        UpdateCurrentPage();
                        UpdateEnableDict(currentPageIndex, true);
                        ReorderVideo();
                        RestMixConfig();
                    }
                    else
                    {
                        panel.Visible = false;
                    }

                    UpdatePageButton();
                }
                else
                {
                    if (foucseNameList.Count < this.MaxFocuseVideoCount)
                    {
                        if (userName != this.focusUser)
                        {
                            panel.Width = smallVideoWidth;
                            panel.Height = smallVideoHeight;
                            rightPanel.Controls.Add(panel);
                            panel.Location = new Point(0,
                                (smallVideoHeight + videoSpace) * (rightPanel.Controls.Count - 1));
                        }
                        else
                        {
                            panel.Width = this.Width - rightPanel.Width - videoSpace * 2;
                            panel.Height = this.Height - videoSpace * 2;
                            panel.Location = new Point(videoSpace, videoSpace);
                        }
                        foucseNameList.Add(userName);
                        ReorderVideo();
                        RestMixConfig();
                    }
                    else
                    {
                        panel.Visible = false;
                    }
                    UpdatePageButton();

                }

                //添加状态栏
                var statusControl = new VideoUserStatusControl();
                statusControl.setMicroStatus(false);
                statusControl.setCameraStatus(false);
                panel.Controls.Add(statusControl);
                statusControl.Location = new Point(panel.Width - 55, panel.Height -24);
                statusControl.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            }
        }

        public void UpdateVideoUserCameraStatus(string userId, bool isMute) {
            if (videoDic.ContainsKey(userId)) {
                var statusControl = videoDic[userId].GetStatusControl();
                statusControl.setCameraStatus(isMute);
            }
        }

        public void UpdateVideoUserMicroStatus(string userId, bool isMute) {
            if (videoDic.ContainsKey(userId))
            {
                var statusControl = videoDic[userId].GetStatusControl();
                statusControl.setMicroStatus(isMute);
            }
        }

        private void Panel_Click(object sender, EventArgs e)
        {
            if (userList1 == null)
            {
            }
            else
            {
                userList1.Hide();
            }
        }

        private void Panel_Paint(object sender, PaintEventArgs e)
        {
            var p = sender as UserVideoItem;
            if (p.Name == TRTC.VideoMainForm.Focuse)
            {
                ControlPaint.DrawBorder(e.Graphics,
                  p.ClientRectangle,
                   Color.Green,
                  2, ButtonBorderStyle.Solid,
                   Color.Green,
                  2, ButtonBorderStyle.Solid,
                   Color.Green,
                  2, ButtonBorderStyle.Solid,
                   Color.Green,
                  2,
                  ButtonBorderStyle.Solid);
            }
            else
            {
                ControlPaint.DrawBorder(e.Graphics,
                  p.ClientRectangle,
                   Color.Gray,
                  1, ButtonBorderStyle.Solid,
                    Color.Gray,
                  1, ButtonBorderStyle.Solid,
                    Color.Gray,
                  1, ButtonBorderStyle.Solid,
                    Color.Gray,
                  1,
                  ButtonBorderStyle.Solid);
            }





            //}));
            //ControlPaint.DrawBorder(e.Graphics,
            //                     panel.ClientRectangle,
            //                     Color.LightSeaGreen,
            //                     1, ButtonBorderStyle.Solid,
            //                     Color.LightSeaGreen,
            //                     1, ButtonBorderStyle.Solid,
            //                     Color.LightSeaGreen,
            //                     1, ButtonBorderStyle.Solid,
            //                     Color.LightSeaGreen, 1,
            //                     ButtonBorderStyle.Solid);
            //使用红色虚线绘制边框
            //var panel = (Panel)sender;
            //Pen pen1 = new Pen(Color.Red, 1);
            //pen1.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
            //pen1.DashPattern = new float[] { 4f, 2f };
            //e.Graphics.DrawRectangle(pen1, 0, 0, panel.Width - 1, panel.Height - 1);
        }

        private void Panel_MouseClick(object sender, MouseEventArgs e)
        {
            if (TCommon.AppContext.isHost == false)
                return;

            if (e.Button == MouseButtons.Right)
            {
                var panel = (UserVideoItem)sender;
                if (TCommon.AppContext.isSharingScreen)
                    return;

                bool isMuted = panel.GetStatusControl().IsMuted();

                bool isFocuseUser = panel.Name == TCommon.AppContext.FocusedUser;

                ContextMenuStrip menu = new ContextMenuStrip();   //初始化menu
                menu.Name = panel.Name;
                menu.ItemClicked += Menu_ItemClicked;
                if (panel.Name != TCommon.AppContext.CurrentUser)
                {
                    if (isMuted)
                    {
                        menu.Items.Add("取消静音");
                    }
                    else
                    {
                        menu.Items.Add("静音");
                    }
                }

                if (!isFocuseUser)
                {
                    menu.Items.Add("设为焦点");
                }
                Point formPoint = this.PointToClient(Control.MousePosition);//鼠标相对于窗体左上角的坐标
                menu.Show(this, formPoint);   //在点(e.X, e.Y)处显示menu

            }
        }

        private void Menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            var actionName = e.ClickedItem.Text;
            var menu = (ContextMenuStrip)sender;
            string inputMsg = string.Empty;
            var action = new ActionEntity();
            string actionString = string.Empty;
            byte[] data;
            switch (actionName)
            {
                case "设为焦点":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":113{3}", "{", TRTC.VideoMainForm.roomId1, menu.Name, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);

                    action.ActionId = HostAction.FocuseUser;
                    action.UserId = menu.Name;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    var sucess = mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    SetFocuseUser(menu.Name);
                    TRTC.VideoMainForm.Focuse = menu.Name;
                    FocusedUserChanged?.Invoke(menu.Name);
                    Task.Factory.StartNew(() =>
                    {
                        var manager = new ServiceManager();
                        manager.SetFocuseUser(TCommon.AppContext.LocalRoomId, menu.Name);
                    });
                    break;
                case "静音":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":111{3}", "{", TRTC.VideoMainForm.roomId1, menu.Name, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    if (videoDic.ContainsKey(menu.Name)) {
                        var statusControl = videoDic[menu.Name].GetStatusControl();
                        statusControl.SetMuteStatus(true);
                    }
                    action.ActionId = HostAction.MuteUser;
                    action.UserId = menu.Name;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    break;
                case "取消静音":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":112{3}", "{", TRTC.VideoMainForm.roomId1, menu.Name, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    if (videoDic.ContainsKey(menu.Name))
                    {
                        var statusControl = videoDic[menu.Name].GetStatusControl();
                        statusControl.SetMuteStatus(false);
                    }
                    action.ActionId = HostAction.UnMuteUser;
                    action.UserId = menu.Name;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    break;
            }
        }

        private void Panel_VisibleChanged(object sender, EventArgs e)
        {
            var panel = (UserVideoItem)sender;
            if (panel.Visible)
            {
                mTRTCCloud.muteRemoteVideoStream(panel.Name, false);
            }
            else
            {
                mTRTCCloud.muteRemoteVideoStream(panel.Name, true);
            }
        }

        private void RestMixConfig()
        {
            VideoLayoutChanged?.Invoke();
        }
        public void SetFocuseUser(string userName)
        {
            if (videoDic.ContainsKey(userName))
            {
                TCommon.AppContext.FocusedUser = userName;
                this.focusUser = userName;

                if (TCommon.AppContext.isSharingScreen) {
                    return;
                }

                if (isMaximized)
                {
                    var name = maximizeCach.Item4;
                    if (videoDic.ContainsKey(name))
                    {
                        ToggleMaximize(videoDic[name]);
                    }
                }

                if (userName != focusUser && focusUser != "")
                {
                    if (!videoDic.ContainsKey(focusUser))
                    {

                    }
                    else
                    {
                        videoDic[focusUser].Visible = false;
                        this.Controls.Remove(videoDic[focusUser]);
                    }

                }
                //if (layoutType == VideoLayoutType.Normal)
                //{
                //    ToggleLayout();
                //}
                UpdateCurrentPage();
                UpdateEnableDict(currentPageIndex, true);
                ReorderVideo();
                RestMixConfig();
            }

            //isFullScreen = false;
            //if (sender1 != null)
            //{
            //    ToggleMaximize(sender1);
            //}

            //sender1 = null;
        }

        public void AddSharePanel(string userName)
        {
            if (screenSharePanel == null)
            {
                screenSharePanel = new Panel();
                screenSharePanel.Dock = DockStyle.Fill;
                screenSharePanel.Width = this.Width;
                screenSharePanel.Height = this.Height;
                screenSharePanel.Location = new Point(0, 0);
                this.Controls.Add(screenSharePanel);
                screenSharePanel.Visible = false;
            }

            if (!shareDic.ContainsKey(userName))
            {
                var panel = new Panel();
                panel.DoubleClick += PanelOnDoubleClick;
                panel.BackColor = Color.Black;
                panel.Tag = userName;
                panel.Dock = DockStyle.Fill;
                shareDic[userName] = panel;

                this.screenSharePanel.Controls.Add(panel);

                if (shareDic.Count > 0)
                {
                    this.screenSharePanel.Visible = true;
                    this.screenSharePanel.BringToFront();
                }

                foreach (var key in videoDic.Keys)
                {
                    if (key != userName)
                        videoDic[key].Visible = false;
                }

                if (videoDic.ContainsKey(userName))
                {
                    var videoPanel = videoDic[userName];
                    if (videoPanel.Parent != null)
                    {
                        if (videoPanel.Parent.Name == "rightPanel")
                        {
                            rightPanel.Controls.Remove(videoPanel);
                            Tuple<int, int, Point, Control> tuple = new Tuple<int, int, Point, Control>(videoPanel.Width, videoPanel.Height, videoPanel.Location, rightPanel);
                            shareCachDic[userName] = tuple;
                        }
                        else
                        {
                            this.Controls.Remove(videoPanel);
                            Tuple<int, int, Point, Control> tuple = new Tuple<int, int, Point, Control>(videoPanel.Width, videoPanel.Height, videoPanel.Location, this);
                            shareCachDic[userName] = tuple;
                        }

                        videoPanel.Width = smallVideoWidth;
                        videoPanel.Height = smallVideoHeight;

                        //videoPanel.Controls[1].Visible = false;

                        var innerPanel = videoPanel.GetVideoPanel();
                        bool hasClosePic = false;
                        PictureBox picture = null;
                        foreach (var control in innerPanel.Controls) {
                            if (control is PictureBox pic) {
                                hasClosePic = true;
                                picture = control as PictureBox;
                                break;
                            }
                        }

                        if (!hasClosePic)
                        {
                            picture = new PictureBox();
                            picture.BackColor = Color.Transparent;
                            picture.Click += Picture_Click;
                            picture.SizeMode = PictureBoxSizeMode.StretchImage;
                            picture.Size = new Size(15, 15);
                            picture.Location = new Point(videoPanel.Width - picture.Width - 5, 0);
                            picture.Image = Resources.close_meeting;
                            picture.Name = "close";
                            videoPanel.Location = new Point(screenSharePanel.Width - panel.Width, screenSharePanel.Height - panel.Height);
                            videoPanel.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
                            videoPanel.GetVideoPanel().Controls.Add(picture);
                        }
                        else
                        {
                            picture.Visible = true;
                        }
                        //videoPanel.Controls.Add(picture);

                        //var fullpicture = new PictureBox();
                        //fullpicture.Click += FullScreenClick;
                        //fullpicture.SizeMode = PictureBoxSizeMode.StretchImage;
                        //fullpicture.Size = new Size(24, 24);
                        //fullpicture.Location = 
                        //    new Point(screenSharePanel.Width - fullpicture.Width - 10, 10);
                        //fullpicture.Anchor = AnchorStyles.Right | AnchorStyles.Top;
                        //fullpicture.Image = Resources.enterfull;
                        //fullpicture.Tag = userName;
                        //screenSharePanel.Controls.Add(fullpicture);
                        //fullpicture.BringToFront();

                        panel.Controls.Add(videoPanel);
                    }
                }
                ReorderShare();
                RestMixConfig();
            }
        }

        private void Picture_Click(object sender, EventArgs e)
        {
            var picture = (PictureBox)sender;
            picture.Parent.Parent.Visible = false;
            picture.Visible = false;
        }

        private void FullScreenClick(object sender, EventArgs e)
        {
            //isFullScreen = !isFullScreen;
            //FullScreenChanged?.Invoke(isFullScreen);

            //var fullBtn = (PictureBox)sender;
            //if (isFullScreen)
            //{
            //    fullBtn.Image = Resources.exitfull;
            //}
            //else
            //{
            //    fullBtn.Image = Resources.enterfull;
            //}
            ToggleFullScreen();
        }

        public void ToggleFullScreen()
        {
            isFullScreen = !isFullScreen;
            FullScreenChanged?.Invoke(isFullScreen);

            var fullBtn = this.fullscreenButton;
            if (isFullScreen)
            {
                fullBtn.SetImage(Resources.exitfull);
            }
            else
            {
                fullBtn.SetImage(Resources.enterfull);
            }
        }

        public void RemoveSharePanel(string userName)
        {
            if (shareDic.ContainsKey(userName))
            {
                var panel = shareDic[userName];
                this.screenSharePanel.Controls.Remove(panel);
                if (panel.Controls.Count > 0)
                {
                    var videoItem = panel.Controls[0] as UserVideoItem;
                    var smallPanel = videoItem.GetVideoPanel();
                    panel.Controls.Remove(videoItem);
                    var tuple = shareCachDic[userName];
                    videoItem.Width = tuple.Item1;
                    videoItem.Height = tuple.Item2;
                    videoItem.Location = tuple.Item3;
                    tuple.Item4.Controls.Add(videoItem);
                    Control closeBtn = null;
                    foreach (var control in smallPanel.Controls)
                    {
                        if (control is PictureBox picture)
                        {
                            if (picture.Name == "close")
                            {
                                closeBtn = picture;
                                break;
                            }
                        }
                    }
                    if (closeBtn != null)
                    {
                        smallPanel.Controls.Remove(closeBtn);
                    }
                }

                shareDic.Remove(userName);
                screenSharePanel.Visible = false;
                ReorderShare();
                RestMixConfig();
            }

            if (shareDic.Count == 0)
            {
                if (this.screenSharePanel != null)
                    this.screenSharePanel.Visible = false;
                foreach (var key in videoDic.Keys)
                {
                    videoDic[key].Visible = true;
                }
                ReorderVideo();
                RestMixConfig();
            }
        }
        public object sender1;
        private void PanelOnDoubleClick(object sender, EventArgs e)
        {
            if (screenSharePanel != null && screenSharePanel.Visible)
                return;

            //if (isFullScreen)
            //    return;
            if (userList1 == null)
            {
            }
            else
            {
                userList1.Hide();
            }

            //ToggleFullScreen();
            ToggleMaximize(sender);
        }
        private void ToggleMaximize(object sender)
        {
            var panel = (UserVideoItem)sender;
            if (layoutType == VideoLayoutType.Normal)
            {
                if (!isMaximized)
                {
                    maximizeCach = new Tuple<int, int, Point, string>(panel.Width, panel.Height, panel.Location, panel.Name);
                    panel.Dock = DockStyle.Fill;
                    panel.BringToFront();
                    isMaximized = true;
                }
                else
                {
                    panel.Dock = DockStyle.None;
                    isMaximized = false;
                    ReorderVideo();
                }
                foreach (var key in normalScreenUsers)
                {
                    //最大化时Mute视频流
                    if (isMaximized)
                    {
                        if (key != panel.Name)
                        {
                            videoDic[key].Visible = false;
                        }
                    }
                    else
                    {
                        videoDic[key].Visible = true;
                    }
                }

            }
            else
            {
                if (!isMaximized)
                {
                    if (panel.Parent.Name == "rightPanel")
                    {
                        maximizeParentCach = rightPanel;
                        rightPanel.Controls.Remove(panel);
                        this.Controls.Add(panel);
                    }
                    else
                    {
                        maximizeParentCach = this;
                    }
                    maximizeCach = new Tuple<int, int, Point, string>(panel.Width, panel.Height, panel.Location, panel.Name);
                    panel.Width = this.Width - videoSpace * 2;
                    panel.Height = this.Height - videoSpace * 2;
                    panel.Location = new Point(videoSpace, videoSpace);
                    panel.BringToFront();
                    isMaximized = true;
                }
                else
                {
                    this.Controls.Remove(panel);
                    //panel.Width = maximizeCach.Item1;
                    //panel.Height = maximizeCach.Item2;
                    //panel.Location = maximizeCach.Item3;
                    isMaximized = false;
                    maximizeParentCach.Controls.Add(panel);
                    ReorderVideo();
                }

                foreach (var key in foucseNameList)
                {
                    //最大化时Mute视频流
                    if (isMaximized)
                    {
                        if (key != panel.Name)
                        {
                            videoDic[key].Visible = false;
                        }
                    }
                    else
                    {
                        videoDic[key].Visible = true;
                    }
                }

                if (isMaximized && focusUser != maximizeCach.Item4)
                {
                    videoDic[focusUser].Visible = false;
                }
                else
                {
                    videoDic[focusUser].Visible = true;
                }
            }
        }

        //public void ViewUserVideo(string userName)
        //{
        //    if (videoDic.Count <= 1)
        //        return;

        //    var panel = videoDic[userName];
        //    if (layoutType == VideoLayoutType.Normal)
        //    {
        //        if (!isMaximized)
        //        {
        //            maximizeCach = new Tuple<int, int, Point, string>(panel.Width, panel.Height, panel.Location, panel.Name);
        //            panel.Width = this.Width;
        //            panel.Height = this.Height;
        //            panel.Location = new Point(0, 0);
        //            panel.BringToFront();
        //            isMaximized = true;
        //        }
        //        else
        //        {
        //            panel.Width = maximizeCach.Item1;
        //            panel.Height = maximizeCach.Item2;
        //            panel.Location = maximizeCach.Item3;
        //            isMaximized = false;
        //        }
        //    }
        //    else
        //    {
        //        if (!isMaximized)
        //        {
        //            if (panel.Parent.Name == "rightPanel")
        //            {
        //                maximizeParentCach = rightPanel;
        //                rightPanel.Controls.Remove(panel);
        //                this.Controls.Add(panel);
        //            }
        //            else
        //            {
        //                maximizeParentCach = this;
        //            }
        //            maximizeCach = new Tuple<int, int, Point, string>(panel.Width, panel.Height, panel.Location, panel.Name);
        //            panel.Width = this.Width - videoSpace * 2;
        //            panel.Height = this.Height - videoSpace * 2;
        //            panel.Location = new Point(videoSpace, videoSpace);
        //            panel.BringToFront();
        //            isMaximized = true;
        //        }
        //        else
        //        {
        //            this.Controls.Remove(panel);
        //            panel.Width = maximizeCach.Item1;
        //            panel.Height = maximizeCach.Item2;
        //            panel.Location = maximizeCach.Item3;
        //            isMaximized = false;
        //            maximizeParentCach.Controls.Add(panel);
        //        }
        //    }
        //}

        private void UpdatePageButton()
        {
            //if (screenSharePanel != null && screenSharePanel.Visible == true)
            //{
            //    ButtonChanged?.Invoke(false, false);
            //    return;
            //}

            //if (layoutType == VideoLayoutType.Normal)
            //{
            //    if (videoDic.Count > MaxNormalVideoCount)
            //    {
            //        ButtonChanged?.Invoke(true, false);
            //    }
            //    else {
            //        ButtonChanged?.Invoke(false, false);
            //    }
            //}
            //else if (layoutType == VideoLayoutType.Focus)
            //{
            //    if (videoDic.Count > MaxFocuseVideoCount + 1)
            //    {
            //        ButtonChanged?.Invoke(false, true);
            //    }
            //    else
            //    {
            //        ButtonChanged?.Invoke(false, false);
            //    }
            //}
        }

        private void ReorderVideo(bool reAdd = false)
        {
            if (screenSharePanel != null && screenSharePanel.Visible)
                return;

            if (this.layoutType == VideoLayoutType.Normal)
            {
                RowSize = MaxNormalVideoCount;
                var count = normalScreenUsers.Count;
                var columnCount = Math.Ceiling(Math.Sqrt(count));
                var rowCount = (int)Math.Ceiling(count / (float)columnCount);
                var panelWidth = (this.Width - videoSpace * (columnCount - 1)) / columnCount;
                var panelHeight = (this.Height - videoSpace * (columnCount - 1)) / rowCount;
                for (int i = 0; i < normalScreenUsers.Count; i++)
                {
                    var rowIndex = i / (int)columnCount;
                    var columnIndex = i % (int)columnCount;
                    var panel = videoDic[normalScreenUsers[i]];

                    if (!isMaximized)
                    {
                        panel.Width = (int)panelWidth;
                        panel.Height = (int)panelHeight;
                        var x = (panel.Width + videoSpace) * columnIndex;
                        var y = (panel.Height + videoSpace) * rowIndex;
                        panel.Location = new Point((int)x, (int)y);
                        if (panel.Visible == false)
                        {
                            panel.Visible = true;
                        }
                    }
                    else
                    {
                        if (panel.Name != maximizeCach.Item4)
                        {
                            panel.Width = (int)panelWidth;
                            panel.Height = (int)panelHeight;
                            var x = (panel.Width + videoSpace) * columnIndex;
                            var y = (panel.Height + videoSpace) * rowIndex;
                            panel.Location = new Point((int)x, (int)y);
                        }
                    }
                }
            }
            else
            {
                rightPanel.BringToFront();
                rightPanel.Visible = !isMaximized;
                this.Controls.Add(rightPanel);
                RowSize = MaxFocuseVideoCount;

                var focusPanel = videoDic[focusUser];
                if (!isMaximized || focusPanel.Name != maximizeCach.Item4)
                {
                    focusPanel.Width = this.Width - rightPanel.Width - videoSpace * 2;
                    focusPanel.Height = this.Height - videoSpace * 2;
                    focusPanel.Location = new Point(videoSpace, videoSpace);
                    this.Controls.Add(focusPanel);
                }

                if (!isMaximized)
                {
                    focusPanel.Visible = true;
                }

                if (this.focusUser == "")
                {
                    this.focusUser = HostName;
                }

                for (int i = 0; i < foucseNameList.Count; i++)
                {
                    var key = foucseNameList[i];
                    if (key != this.focusUser)
                    {
                        var panel = videoDic[key];
                        if (!isMaximized || panel.Name != maximizeCach.Item4)
                        {
                            panel.Width = smallVideoWidth;
                            panel.Height = smallVideoHeight;
                            rightPanel.Controls.Add(panel);
                            panel.Location = new Point(0, (smallVideoHeight + videoSpace) * i);
                            if (panel.Visible == false)
                            {
                                panel.Visible = true;
                            }
                        }
                    }
                }
            }

            UpdatePageButton();
        }

        private void UpdateEnableDict(int pageIndex, bool toggleLayout, bool isDelete = false)
        {
            try
            {
                if (pageIndex == currentPageIndex && !toggleLayout)
                    return;

                if (layoutType == VideoLayoutType.Normal)
                {
                    if (!isDelete)
                    {
                        foreach (var key in normalScreenUsers)
                        {
                            videoDic[key].Visible = false;
                            this.Controls.Remove(videoDic[key]);
                        }
                        foreach (var user in normalScreenUsers) {
                            NormalScreenUserChanged?.Invoke(user, false);
                        }
                        normalScreenUsers.Clear();
                    }


                    for (int i = 0; i < MaxNormalVideoCount; i++)
                    {
                        int index = MaxNormalVideoCount * pageIndex + i;
                        if (index < nameList.Count)
                        {
                            if (!videoDic.ContainsKey(nameList[index]))
                                continue;
                            if (!normalScreenUsers.Contains(nameList[index]))
                            {
                                //全屏时不能隐藏焦点视频
                                if (!isMaximized || videoDic[nameList[index]].Name != maximizeCach.Item4)
                                    videoDic[nameList[index]].Visible = false;
                                normalScreenUsers.Add(nameList[index]);
                                NormalScreenUserChanged?.Invoke(nameList[index], true);
                                this.Controls.Add(videoDic[nameList[index]]);
                            }
                        }
                    }
                }
                else
                {
                    videoDic[focusUser].Visible = true;
                    var list = nameList.Where(n => n != this.focusUser).ToList();
                    if (!isDelete)
                    {
                        foreach (var key in foucseNameList)
                        {
                            videoDic[key].Visible = false;
                            this.rightPanel.Controls.Remove(videoDic[key]);
                        }
                        foucseNameList.Clear();
                    }
                    for (int i = 0; i < MaxFocuseVideoCount; i++)
                    {
                        int index = MaxFocuseVideoCount * pageIndex + i;
                        if (index < list.Count)
                        {
                            if (!videoDic.ContainsKey(list[index]))
                                continue;
                            if (!foucseNameList.Contains(list[index]))
                            {
                                foucseNameList.Add(list[index]);
                                videoDic[list[index]].Visible = false;
                                this.rightPanel.Controls.Remove(videoDic[list[index]]);
                            }
                        }
                    }
                }
                currentPageIndex = pageIndex;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("", ex);
            }
        }
        private void UpdateCurrentPage()
        {
            if (currentPageIndex == 0)
            {
                if (layoutType == VideoLayoutType.Normal)
                {
                    // normalScreenUsers.Clear();
                    if (nameList.Contains(focusUser))
                    {
                        nameList.Remove(focusUser);
                        nameList.Insert(0, focusUser);
                    }

                    if (nameList.Contains(TCommon.AppContext.CurrentUser))
                    {
                        nameList.Remove(TCommon.AppContext.CurrentUser);
                        nameList.Insert(0, TCommon.AppContext.CurrentUser);
                    }
                }
                else
                {
                    if (foucseNameList.Contains(TCommon.AppContext.CurrentUser))
                    {
                        foucseNameList.Remove(TCommon.AppContext.CurrentUser);
                        foucseNameList.Insert(0, TCommon.AppContext.CurrentUser);
                    }
                }
            }
        }

        private void ReorderShare()
        {
            try
            {
                var count = shareDic.Count;
                var columnCount = Math.Ceiling(Math.Sqrt(count));
                var rowCount = Math.Ceiling(count / (float)columnCount);
                var panelWidth = (this.Width - videoSpace * (columnCount + 1)) / columnCount;
                var panelHeight = (this.Height - videoSpace * (columnCount + 1)) / rowCount;
                var keys = shareDic.Keys.ToList();
                for (int i = 0; i < shareDic.Keys.Count; i++)
                {
                    var rowIndex = i / (int)columnCount;
                    var columnIndex = i % (int)columnCount;
                    var panel = shareDic[keys[i]];
                    panel.Width = (int)panelWidth;
                    panel.Height = (int)panelHeight;
                    var x = videoSpace + (panel.Width + videoSpace) * columnIndex;
                    var y = videoSpace + (panel.Height + videoSpace) * rowIndex;
                    panel.Location = new Point((int)x, (int)y);
                    if (panel.Controls.Count > 0)
                    {
                        var smallPanel = panel.Controls[0];
                        smallPanel.Location = new Point(panel.Width - smallPanel.Width, panel.Height - smallPanel.Height);
                    }
                }

                UpdatePageButton();
                fullscreenButton.BringToFront();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("", ex);
            }
        }

        private void VideoContainer_SizeChanged(object sender, EventArgs e)
        {
            ReorderShare();
            ReorderVideo();
        }

        public void NormalNextPage()
        {
            var maxPageSize = nameList.Count / MaxNormalVideoCount;
            if (nameList.Count % MaxNormalVideoCount != 0)
            {
                maxPageSize++;
            }

            if (currentPageIndex + 1 == maxPageSize)
                return;

            UpdateEnableDict(currentPageIndex + 1, false);
            //var keys = videoDic.Keys.ToList();
            //if (layoutType == VideoLayoutType.Normal) {
            //    var index = keys.IndexOf(enabledDic.Keys.ToList()[enabledDic.Count -1]);
            //    if (index == videoDic.Count - 1) {
            //        return;
            //    }

            //    var start = index + 1;
            //    var endIndex = start + MaxNormalVideoCount -1;

            //    foreach (var key in enabledDic.Keys) {
            //        enabledDic[key].Visible = false;
            //    }

            //    enabledDic.Clear();
            //    this.Controls.Clear();

            //    for (int i = start; i < start + MaxNormalVideoCount; i++) {
            //        videoDic[keys[i]].Visible = true;
            //        enabledDic[keys[i]] = videoDic[keys[i]];
            //        this.Controls.Add(videoDic[keys[i]]);
            //    }
            //}

            ReorderVideo();
            RestMixConfig();
        }

        public void NormalPrePage()
        {
            if (currentPageIndex == 0)
                return;

            UpdateEnableDict(currentPageIndex - 1, false);

            //var keys = videoDic.Keys.ToList();
            //if (layoutType == VideoLayoutType.Normal)
            //{
            //    var index = keys.IndexOf(enabledDic.Keys.ToList()[0]);
            //    if (index == 0) {
            //        return;
            //    }

            //    var start = index;
            //    if (start - MaxNormalVideoCount >= 0) {
            //        start = start - MaxNormalVideoCount;
            //    }

            //    var endIndex = start + MaxNormalVideoCount;

            //    foreach (var key in enabledDic.Keys)
            //    {
            //        enabledDic[key].Visible = false;
            //    }

            //    enabledDic.Clear();
            //    this.Controls.Clear();

            //    for (int i = start; i < start + MaxNormalVideoCount; i++)
            //    {
            //        videoDic[keys[i]].Visible = true;
            //        enabledDic[keys[i]] = videoDic[keys[i]];
            //        this.Controls.Add(videoDic[keys[i]]);
            //    }
            //}

            ReorderVideo();
            RestMixConfig();
        }

        public void FocuseNextPage()
        {
            var nonFocuseCount = nameList.Count - 1;
            var maxPageSize = nonFocuseCount / MaxFocuseVideoCount;
            if (nonFocuseCount % MaxFocuseVideoCount != 0)
            {
                maxPageSize++;
            }

            if (currentPageIndex + 1 == maxPageSize)
                return;

            UpdateEnableDict(currentPageIndex + 1, false);
            //var tempDict = new SortedDictionary<string, Panel>();
            //foreach (var key in videoDic.Keys) {
            //    if (key != focusUser) {
            //        tempDict[key] = videoDic[key];
            //    }
            //}
            //var keys = tempDict.Keys.ToList();
            //if (layoutType == VideoLayoutType.Focus)
            //{
            //    var index = keys.IndexOf(enableNoneFocuseDic.Keys.ToList()[enableNoneFocuseDic.Count - 1]);
            //    if (index == tempDict.Count - 1)
            //    {
            //        return;
            //    }

            //    var start = index + 1;
            //    var endIndex = start + MaxFocuseVideoCount - 1;

            //    //var focuseIndex = keys.IndexOf(focusUser);
            //    //if (focuseIndex >= start && focuseIndex <= endIndex) {
            //    //    endIndex = endIndex + 1;
            //    //}

            //    foreach (var key in enableNoneFocuseDic.Keys)
            //    {
            //        enableNoneFocuseDic[key].Visible = false;
            //    }

            //    enableNoneFocuseDic.Clear();
            //    if (!string.IsNullOrEmpty(focusUser))
            //    {
            //        enableNoneFocuseDic[focusUser] = videoDic[focusUser];
            //        enableNoneFocuseDic[focusUser].Visible = true;
            //    }
            //    this.Controls.Clear();

            //    for (int i = start; i <= endIndex; i++)
            //    {
            //        tempDict[keys[i]].Visible = true;
            //        enableNoneFocuseDic[keys[i]] = tempDict[keys[i]];
            //        enabledDic[keys[i]] = tempDict[keys[i]];
            //    }
            //}

            ReorderVideo();
            RestMixConfig();
        }

        public void FocusePrePage()
        {
            if (currentPageIndex == 0)
                return;

            UpdateEnableDict(currentPageIndex - 1, false);
            //var keys = videoDic.Keys.ToList();
            //if (layoutType == VideoLayoutType.Focus)
            //{
            //    string firstKey = string.Empty;
            //    if (enableNoneFocuseDic.Keys.ToList()[0] == focusUser)
            //    {
            //        firstKey = enableNoneFocuseDic.Keys.ToList()[1];
            //    }
            //    else
            //    {
            //        firstKey = enableNoneFocuseDic.Keys.ToList()[0];
            //    } 
            //    var index = keys.IndexOf(firstKey);
            //    if (index == 0)
            //    {
            //        return;
            //    }

            //    var start = 0;
            //    if (start - MaxFocuseVideoCount >= 0)
            //    {
            //        start = start - MaxFocuseVideoCount;
            //    }

            //    var endIndex = start + MaxFocuseVideoCount;

            //    var focuseIndex = keys.IndexOf(focusUser);
            //    if (focuseIndex >= start && focuseIndex <= endIndex)
            //    {
            //        endIndex = endIndex + 1;
            //    }

            //    foreach (var key in enableNoneFocuseDic.Keys)
            //    {
            //        enableNoneFocuseDic[key].Visible = false;
            //    }

            //    enableNoneFocuseDic.Clear();
            //    enabledDic.Clear();
            //    enabledDic[focusUser] = videoDic[focusUser];
            //    this.Controls.Clear();

            //    for (int i = start; i < endIndex; i++)
            //    {
            //        videoDic[keys[i]].Visible = true;
            //        enableNoneFocuseDic[keys[i]] = videoDic[keys[i]];
            //        enabledDic[keys[i]] = videoDic[keys[i]];
            //        this.Controls.Add(videoDic[keys[i]]);
            //    }
            //}

            ReorderVideo();
            RestMixConfig();
        }
        //画廊
        //public void layout(TRTC.VideoMainForm videoMain)
        //{
        //    if (sender1 == null)
        //    {
        //        if (string.IsNullOrEmpty(TRTC.VideoMainForm.Focuse))
        //        {

        //        }
        //        else
        //        {
        //            SetFocuseUser(TRTC.VideoMainForm.Focuse);
        //        }
        //    }
        //    else
        //    {
        //        isFullScreen = false;
        //        //ToggleFullScreen1();
        //        ToggleMaximize(sender1);
        //        // videoMain.VideoContainer_FullScreenChanged(false);
        //        sender1 = null;
        //    }

        //}
        public void ToggleFullScreen1()
        {
            FullScreenChanged?.Invoke(isFullScreen);

            var fullBtn = this.fullscreenButton;
            if (isFullScreen)
            {
                fullBtn.SetImage(Resources.exitfull);
            }
            else
            {
                fullBtn.SetImage(Resources.enterfull);
            }
        }
        public void clearNormalScreenUsers()
        {
            if (normalScreenUsers != null)
            {
                foreach (var user in normalScreenUsers)
                {
                    NormalScreenUserChanged?.Invoke(user, false);
                }
                normalScreenUsers.Clear();
                nameList.Clear();
            }

        }

    }


    public enum VideoLayoutType
    {
        Normal,
        Focus
    }
}
